import { CSSRuleObject, styled } from "styledfc";
import Main from "@/components/Main";
import Back from "@/components/Back";
import img from "./img";
import { FlexCss } from "../../utils/styledfc";
import Button from "@/components/Button";
import { FormEvent, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useForm } from "react-form-simple";
import { postLogin, postRegister } from "@/api";
import { Dialog, Toast } from "react-vant";
export interface UserInfo {
    acc: string;
    password: string;
    password2: string;
    nick_name: string;
    img: string;
    sig?: string;
    oldPassword?: string;
}

export default function index() {
    async function handleSubmit(e: FormEvent<HTMLFormElement>) {
        e.preventDefault();
        e.stopPropagation();
        await validate();
        if (type === "login") {
            const res = (await postLogin(model as UserInfo)) as { [key in string]: string | number };
            if (res.code === 400) {
                Dialog.alert({
                    title: res.data,
                    confirmButtonColor: "#ee0a24",
                });
            } else {
                Toast.success("登录成功");
                localStorage.setItem("pet-userInfo", JSON.stringify(res.data));
                navigate("/home");
            }
        } else {
            if (model.password2 !== model.password) {
                Dialog.alert({
                    title: "两次密码不一致",
                    confirmButtonColor: "#ee0a24",
                });
                return;
            }
            const { nick_name, password, acc } = model as UserInfo;
            postRegister({ nick_name, password, acc }).then((res) => {
                const { code, data } = res as { code: number; data: string };
                console.log(code, data);
                if (code === 400) {
                    Dialog.alert({
                        title: data,
                        confirmButtonColor: "#ee0a24",
                    });
                } else {
                    Dialog.confirm({
                        title: "注册成功",
                        message: "是否前往登录",
                        confirmButtonColor: "#ee0a24",
                        onConfirm: () => {
                            navigate("/user/login");
                        },
                    });
                }
            });
        }
    }
    const navigate = useNavigate();
    const { model, render, validate } = useForm<Partial<UserInfo>>({ acc: "", password: "", password2: "", nick_name: "" });
    const renerUsername = render("acc", {
        label: "账号",
        rules: {
            required: "账号不能为空",
        },
    })(<input placeholder="请输入账号" />);

    const renerPassword = render("password", {
        label: "密码",
        rules: { required: "密码不能为空" },
    })(<input type="password" placeholder="请输入密码" />);

    const renerPassword2 = render("password2", {
        label: "密码",
        rules: { required: "密码不能为空" },
    })(<input type="password" placeholder="再次输入密码" />);

    const renerNickname = render("nick_name", {
        label: "昵称",
        rules: { required: "昵称不能为空" },
    })(<input placeholder="请输入昵称" />);
    const [userType, setUserType] = useState<string>("");
    const { type } = useParams();
    useEffect(() => {
        setUserType(type as string);
    }, [type]);
    async function pathTo() {
        navigate(userType === "login" ? "/user/register" : "/user/login", { replace: true });
    }
    return (
        <div className={indexStyle.className}>
            <Back />
            <div className="index__header">
                <div className="index__header-title">
                    <div className="title__h2">{userType === "login" ? "Hi Welcome" : "Hello!"}</div>
                    <div className="title__h1">{userType === "login" ? "Back" : "see You"} </div>
                </div>
                <img src={img.userHeader} />
            </div>
            <Main border={true}>
                <form className="index__form" onSubmit={handleSubmit}>
                    {type === "register" ? (
                        <>
                            {renerNickname}
                            {renerUsername}
                            {renerPassword}
                            {renerPassword2}
                        </>
                    ) : (
                        <>
                            {renerUsername}
                            {renerPassword}
                        </>
                    )}

                    <div className="control">
                        <Button onChange={() => handleSubmit} text={userType === "login" ? "登录" : "注册"} />
                        <Button onChange={pathTo} type="button" text={userType === "login" ? "去注册" : "去登录"} />
                    </div>
                </form>
            </Main>
        </div>
    );
}
const indexStyle = styled({
    fontSize: "16rem",
    backgroundColor: "#a1b275",
    ".index__header": {
        width: "100%",
        height: "150rem",
        ...(FlexCss("center", "space-between") as CSSRuleObject),
        ">img": {
            height: "130rem",
            marginRight: "20rem",
            marginTop: "10rem",
            transform: "translate(-19rem,19rem)",
        },
    },

    ".index__header-title": {
        marginTop: "20rem",
        marginLeft: "40rem",
        color: "white",
        lineHeight: "36rem",

        ".title__h2": {
            fontSize: "26rem",
            fontWeight: "100",
        },

        ".title__h1": {
            fontFamily: "'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif",
            fontSize: "28rem",
            fontWeight: "100",
        },
    },
    ".index__form": {
        height: "calc(100vh - 250rem)",
        width: "100%",
        paddingTop: "30rem",
        "& input": {
            width: "260rem",
            backgroundColor: "transparent",
            border: "none",
            outline: "none",
            marginLeft: "10rem",
        },
        ".react-form-simple-form-item": {
            margin: "0rem",
        },
        ".react-form-simple-error-txt": {
            fontSize: "12rem",
            marginLeft: "10rem",
        },
        ".label-wrap": {
            width: "50rem",
            marginRight: "0rem !important",
        },
        ">div:not(.control)": {
            display: "flex",
            margin: "0 20rem 10rem",
            padding: "20rem 10rem",
            borderBottom: "2rem solid #a1b275",
        },
        ".control": {
            marginTop: "40rem",
        },
    },
});
